package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContext;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.system.db4.model.result.ShopOwnerInfoResult;
import cn.stylefeng.guns.sys.modular.system.db4.service.BizShopService;
import cn.stylefeng.guns.sys.modular.system.entity.BtyCwFine;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyCwFineMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyGoodsPayMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyCwFineParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyCwFineResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyCwFineService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 财务罚款 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-01-18
 */
@Service
public class BtyCwFineServiceImpl extends ServiceImpl<BtyCwFineMapper, BtyCwFine> implements BtyCwFineService {

    @Resource
    private BizShopService bizShopService;
    @Resource
    private BtyGoodsPayMapper btyGoodsPayMapper;

    @Override
    public void add(BtyCwFineParam param){
        BtyCwFine entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyCwFineParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyCwFineParam param){
        BtyCwFine oldEntity = getOldEntity(param);
        BtyCwFine newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyCwFineResult findBySpec(BtyCwFineParam param){
        return null;
    }

    @Override
    public List<BtyCwFineResult> findListBySpec(BtyCwFineParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyCwFineParam param){
        //获取当前登陆者
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();

        Page pageContext = getPageContext();
        IPage page = null;
        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            page = this.baseMapper.customPageList(pageContext, param, null);
        }else if (roleNames.contains("应收会计")){
            page = this.baseMapper.customPageList(pageContext, param, name);
        }
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 同步店名
     * @param month
     * @return
     */
    @Override
    public ResponseData synData(String month) {
        //获取需要同步的店名(应收会计)
        List<Map> mapList = baseMapper.getMapList();
        //店长信息
        Map<String, ShopOwnerInfoResult> resultMap = bizShopService.shopOwnerInfoList();

        if (ToolUtil.isNotEmpty(mapList)){
            for (Map map : mapList) {
                BtyCwFine entity = new BtyCwFine();
                entity.setMonth(month);//月份
                entity.setCwry(map.get("cwry").toString());//财务人员
                entity.setDm(map.get("dm").toString());//店名
                if (ToolUtil.isNotEmpty(map.get("yaoma"))){
                    String yaoma = map.get("yaoma").toString();
                    entity.setYaoma(yaoma);//妖码

                    if (ToolUtil.isNotEmpty(resultMap.get(yaoma))){
                        entity.setShopownerView(resultMap.get(yaoma).getShopownerView());//店长
                        entity.setMobile(resultMap.get(yaoma).getMobile());//店长手机
                    }
                }
                entity.setMdbh(map.get("mdbh").toString());//门店编号
                entity.setCwm(map.get("cwm").toString());//财务码
                //查询表中是否有该店
                int con = baseMapper.getCon(entity);
                if (con != 0){
                    baseMapper.updateByYm(entity);
                }else {
                    this.save(entity);
                }
            }
        }else {
            return ResponseData.error(1, "当前登录人当前月份目前没有要初始化数据的门店");
        }

        return ResponseData.success();
    }

    /**
     * 店名列表
     * @return
     */
    @Override
    public ResponseData dmList() {
        //获取当前登陆者
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<Map> list = new ArrayList<>();

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            list = this.baseMapper.dmList(null);
        }else if (roleNames.contains("应收会计")){
            list = this.baseMapper.dmList(name);
        }
        return ResponseData.success(list);
    }

    /**
     * 批量审核
     * @param month
     * @return
     */
    @Override
    public ResponseData batchAudit(String month) {
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int monthDay = calendar.get(Calendar.DAY_OF_MONTH);
        if (monthDay > 10){
            return ResponseData.error(201,"每月10日前可审核！");
        }else if (monthDay <= 10){
            //获取当前登陆者
            String name = LoginContextHolder.getContext().getUser().getName();
            //当前登陆者角色
            List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
            //获取有财务罚款，有罚款人，且待审核的当月数据
            List<BtyCwFine> list = new ArrayList<>();

            if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
                list = baseMapper.getAuditList(month, null);
            }else if (roleNames.contains("应收会计")){
                list = baseMapper.getAuditList(month, name);
            }
            if (ToolUtil.isNotEmpty(list)){
                //每150条保存一次
                for(int i = 0; i < list.size();){
                    int i2 = (i + 150);
                    i2 = i2 > list.size() ? list.size() : i2;
                    List<BtyCwFine> sub = list.subList(i, i2);
                    //将这些数据改为通过状态
                    baseMapper.updateList(sub);
                    i = i2;
                }
            }
        }
        return ResponseData.success();
    }

    /**
     * 审核通过
     * @param id
     * @return
     */
    @Override
    public ResponseData audit(Long id) {
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int monthDay = calendar.get(Calendar.DAY_OF_MONTH);
        if (monthDay > 10){
            return ResponseData.error(201,"每月10日前可审核！");
        }else if (monthDay <= 10){
            //查询该数据状态
            BtyCwFine cwFine = baseMapper.selectById(id);
            //待审核状态
            if (cwFine.getStatus() == 0){
                if (ToolUtil.isEmpty(cwFine.getDzName())){
                    return ResponseData.error(201,"罚款人不可为空！");
                }else if (ToolUtil.isEmpty(cwFine.getCwDeduction()) || cwFine.getCwDeduction().compareTo(BigDecimal.ZERO) == 0){
                    return ResponseData.error(201,"财务罚款不可为空或为0！");
                }else {
                    baseMapper.auditById(id);
                }
            }else {
                return ResponseData.error(201,"待审核状态才可审核！");
            }


            //待审核状态，且财务罚款不为空不为0，且已选择罚款人
//            if (cwFine.getStatus() == 0 && ToolUtil.isNotEmpty(cwFine.getCwDeduction()) && cwFine.getCwDeduction().compareTo(BigDecimal.ZERO) != 0){
//                baseMapper.auditById(id);
//            }else {
//                return ResponseData.error(201,"待审核状态，且财务罚款不为空、不为0时，才可审核！");
//            }
        }
        return ResponseData.success();
    }

    /**
     * 撤回
     * @param id
     * @return
     */
    @Override
    public ResponseData recall(Long id) {
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int monthDay = calendar.get(Calendar.DAY_OF_MONTH);
        if (monthDay > 10){
            return ResponseData.error(201,"每月10日前可撤回！");
        }else if (monthDay <= 10){
            //查询该数据状态
            BtyCwFine cwFine = baseMapper.selectById(id);
            if (cwFine.getStatus() == 0){
                return ResponseData.error(201,"待审核状态无需撤回！");
                //已同步货赔
            }else if (cwFine.getStatus() == 2){
                //将货赔审核中罚款金额改为空
                btyGoodsPayMapper.updateCwDed(cwFine.getMonth(), cwFine.getDm(), cwFine.getMdbh());
            }
            //修改状态为待审核
            baseMapper.recallById(id);
        }
        return ResponseData.success();
    }

    /**
     * 编辑财务罚款
     * @param param
     */
    @Override
    public void editById(BtyCwFineParam param) {
        BtyCwFine oldEntity = getOldEntity(param);
        BtyCwFine newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        newEntity.setUpdateUser(LoginContextHolder.getContext().getUserId());
        baseMapper.editById(newEntity);
    }

    /**
     * 同步到货赔审核
     * @param month
     * @return
     */
    @Override
    public ResponseData synGoodspay(String month) {
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int monthDay = calendar.get(Calendar.DAY_OF_MONTH);
        if (monthDay > 10){
            return ResponseData.error(201,"每月10日前可同步！");
        }else if (monthDay <= 10){
            //获取当前登陆者姓名
            String name = LoginContextHolder.getContext().getUser().getName();
            //当前登陆者角色
            List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();

            //获取所有审核通过的数据
            List<Map> list = new ArrayList<>();
            if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
                list = baseMapper.getList(month, null);
            }else if (roleNames.contains("应收会计")){
                list = baseMapper.getList(month, name);
            }

            int num = 0;//同步失败数量
            //将财务罚款同步到货赔审核中
            if (ToolUtil.isNotEmpty(list)){
                //每150条保存一次
//                for(int i = 0; i < list.size();){
//                    int i2 = (i + 150);
//                    i2 = i2 > list.size() ? list.size() : i2;
//                    List<Map> sub = list.subList(i, i2);
//                    //修改财务罚款
//                    btyGoodsPayMapper.updateList(sub);
//                    //修改财务罚款表状态为已同步货赔
//                    baseMapper.updateCwFine(sub);
//                    i = i2;
//                }
                for (Map map : list) {
                    //修改财务罚款
                    int i = btyGoodsPayMapper.updateMap(map);
                    if (i != 0){
                        //修改财务罚款表状态为已同步货赔
                        baseMapper.updateFine(map);
                    }else if (i == 0){
                        num = num + 1;
                    }
                }
            }
            if (num > 0){
                return ResponseData.error(201, "货赔审核中有不存在的门店，请联系成本会计同步店名后，再次进行同步到货赔！");
            }
        }

        return ResponseData.success();
    }

    private Serializable getKey(BtyCwFineParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyCwFine getOldEntity(BtyCwFineParam param) {
        return this.getById(getKey(param));
    }

    private BtyCwFine getEntity(BtyCwFineParam param) {
        BtyCwFine entity = new BtyCwFine();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
